<template>
  <div class="my-audio">
    <!-- 左侧歌名、歌手名 -->
    <div class="player-left">
      <img v-lazy="music.songImg" v-show="isMusic" @click="controlModal(true)">
      <div class="player-info" v-show="isMusic">
        <div class="sing-name textmore-hidden" :title="music.songName">
          {{ music.songName }}
        </div>
        <div class="singer-name text-hidden font-12">
          <span v-for="singer in music.singerName" :key="singer.id">
            {{ singer.name }}
          </span>
        </div>
      </div>
    </div>
    <!-- 播放器 -->
    <div class="player-center">
      <!-- 按钮 -->
      <div class="player-bar">
        <!-- <a-tooltip
          placement="top"
          :visible="showTip"
          :arrowPointAtCenter="true"
        >
          <template slot="title">
            <span>{{ playText }}</span>
          </template> -->
        <button class="first-btn" @click="changePlayType">
          <i
            class="iconfont"
            :class="[
              className,
              isMusic ? '' : 'disabled-color'
            ]"
          ></i>
        </button>
        <!-- </a-tooltip> -->
        <!-- 上一首 -->
        <button class="prev-btn" @click="playMusic('prev')">
          <a-icon type="step-backward" :class="[isMusic ? '' : 'disabled-color']" />
        </button>
        <!-- 播放 -->
        <i
          class="iconfont pointer"
          style="font-size: 30px"
          :class="[
            isPlay ? 'icon-zanting' : 'icon-zanting1',
            isMusic ? '' : 'disabled-color'
          ]"
          @click="playMusic('play')"
        ></i>
        <!-- 下一首 -->
        <button class="next-btn" @click="playMusic('next')">
          <a-icon type="step-forward" :class="[isMusic ? '' : 'disabled-color']" />
        </button>
        <!-- 喜欢❤ -->
        <button class="love-btn">
          <a-icon type="heart" :class="[isMusic ? '' : 'disabled-color']" />
        </button>
      </div>
      <!-- 进度条 -->
      <a-slider
        :sliderStyle="{
          width: '400px',
          margin: '0 10px'
        }"
        :sideTime="isMusic"
        :value="sliderVal"
        :disabled="disabled"
        :max="maxTime"
        :tipFormatter="() => this.curTime"
        :currentTime="curTime"
        :duration="durTime"
        @changeValue="changeValue"
      />
    </div>
    <!-- 右侧操作栏 -->
    <div class="player-right">
      <!-- 下载 -->
      <!-- <button class="down-btn" v-show="isMusic">
        <a-icon type="arrow-down" />
      </button> -->
      <!-- 音量 -->
      <button
        class="volume-btn"
        v-show="isMusic"
        @mouseenter="volumeModal = true"
        @mouseleave="volumeModal = false"
      >
        <div class="hover-modal" v-show="volumeModal">
          <a-slider
            :vertical="true"
            :sliderStyle="{
              height: '100px',
              'marginBottom': '12px'
            }"
            :value="volume"
            :tipFormatter="() => volume"
            @changeValue="changeVolume"
          />
        </div>
        <i
          class="iconfont"
          @click="banNotes"
          :class="[banVolume ? 'icon-jingyin' : 'icon-yinliang']"
        ></i>
      </button>
      <!-- 播放列表 -->
      <button class="player-btn" v-show="isMusic" @click="showPlayerList">
        <a-icon type="menu" />
      </button>
    </div>
    <!-- 音频播放 -->
    <audio-player
      ref="player"
      @onended="playMusic('next')"
      @oncanplay="oncanplay"
      @ontimeupdate="ontimeupdate"
      @ondurationchange="ondurationchange"
    />

    <!-- 抽屉 -->
    <a-drawer
      title="当前播放"
      width="512"
      :placement="placement"
      :closable="true"
      :visible="visible"
      wrapClassName="drawer"
      @close="visible = false;"
    >
      <div class="list-header">
        <div class="total-song">
          总{{ audioList.length ? audioList.length : 0 }}首
        </div>
      </div>
      <MyList :columns="columns" :dataSource="audioList" :showHeader="false" />
    </a-drawer>

    <!-- 当前播放歌曲详情 -->
    <play-info
      :showPlayModal="showLyric"
      :songInfo="music"
      :dTime="maxTime"
      @goAlbum="goAlbum"
      @controlModal="controlModal"
    >
    </play-info>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { formatTime } from '@/utils/figure';
import { randam, throttle } from '@/utils/optimize';
import { musicUrl } from '@/api/music';
import { Drawer } from 'ant-design-vue';
import MyList from '@/components/Detail/List';
import Slider from '../Library/Slider';
import AudioPlayer from '../Player/AudioPlayer';
import PlayInfo  from '../Detail/PlayInfo';

export default {
  name: 'myAudio',
  components: {
    MyList,
    PlayInfo,
    AudioPlayer,
    ASlider: Slider,
    ADrawer: Drawer,
    // ATooltip: Tooltip
  },

  provide() {
    return {
      // 因为provide/inject传值不是响应式,这样写可以解决响应式问题
      isRotato: () => this.isPlay,
      timeChange: () => this.currentTime,
      // 孙子组件通过该事件显示隐藏Modal
      isModal: this.controlModal,
      // 点击歌词快进和快退
      changeTime: this.changeValue
    }
  },

  data() {
    return {
      // 显示隐藏抽屉
      visible: false,
      placement: 'right',
      columns: [
        {
          title: '',
          dataIndex: 'index',
          key: 'index',
          width: 30,
          scopedSlots: { customRender: 'key' }
        },
        {
          title: '音乐标题',
          dataIndex: 'name',
          key: 'name',
          ellipsis: true,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '歌手',
          dataIndex: 'ar',
          key: 'ar',
          width: 150,
          ellipsis: true,
          scopedSlots: { customRender: 'ar' }
        },
        {
          title: '时长',
          dataIndex: 'duration',
          key: 'duration',
          ellipsis: true,
          width: 80,
          scopedSlots: { customRender: 'duration' }
        },
      ],
      // 是否禁用
      disabled: true,
      // inputValue1: 1,
      // 控制播放按钮显示隐藏
      isPlay: false,
      // 判断是循环播放(1)、单曲循环(2)或随机播放(3),默认循环播放
      playType: 1,
      // 是否禁音播放
      banVolume: false,
      // 控制音量控制框
      volumeModal: false,
      // 控制音量大小
      volume: 50,
      // 音乐地址
      musicUrl: '',
      // 播放时间
      currentTime: 0,
      // 播放总时长
      duration: 0,
      // music信息
      music: {},
      // 滑块值
      sliderVal: 0,
      // 控制歌词弹框显示隐藏
      showLyric: false
    };
  },

  computed: {
    ...mapState({
      audioList: state => state.detail.audioList,
      audioId: state => state.detail.audioId,
      isPlayed: state => state.main.isPlayed
    }),
    isMusic() {
      // return this.music && Object.keys(this.music).length
      return this.audioId && Object.keys(this.audioId).length;
    },
    className() {
      if (this.playType === 1) {
        return 'icon-shunxubofang';
      } else if (this.playType === 2) {
        return 'icon-liebiaoxunhuan';
      } else if (this.playType === 3) {
        return 'icon-danquxunhuan1';
      } else {
        return 'icon-suijibofang';
      }
    },
    // 格式化后起始时间
    curTime() {
      const time = formatTime(this.currentTime);
      return `${time.min}:${time.max}`;
      //   console.log(value);
      //   // 避免重复给isPlay赋值true,只需要改变一次状态
      //   if (value !== '00:00' && this.isPlay) {
      //     this.isPlay = false;
      //     // return;
      //   }
      //   this.isPlay = true;
      // }
    },
    // 格式化后总时间
    durTime() {
      const time = formatTime(this.duration);
      return `${time.min}:${time.max}`;
    },
    minTime() {
      return Math.floor(this.currentTime);
    },
    maxTime() {
      return Math.floor(this.duration);
    },
    // audio
    audioRef() {
      return this.$refs.player.$refs.playerBox;
    }
  },

  watch: {
    audioId: {
      handler(value) {
        if (value && Object.keys(value).length) {
          this.reduceMusic(value);
        }
      }
      // deep: true
    },
    // 判断是否需要立即播放歌曲
    isPlayed: {
      handler(value) {
        if (value) {
          this.getMusicUrl();
          this.isPlay = value;
        }
      },
      deep: true
    },
    '$route.name': {
      handler(value) {
        if (value === 'videodetail') {
          // 暂停播放歌曲
          this.audioRef.pause();
        }
      }
    }
  },

  methods: {
    // 时长发生了变化
    ondurationchange(info) {
      this.duration = info;
      // 存储当前播放歌曲信息
      localStorage.setItem('currentSong', JSON.stringify(this.audioId));
      // 存储当前播放列表
      localStorage.setItem('recentPlay', JSON.stringify(this.audioList));
    },
    // 开始播放音乐事件
    oncanplay() {
      console.log('我播放啦');
      this.$store.commit('main/ISPLAYED', false);
      // 隐藏歌词loading
      this.$store.commit('main/ISLOAD', false);
      this.disabled = false;
      this.audioRef.volume = 0.5;
    },
    // 播放位置发生了变动
    ontimeupdate(time) {
      this.sliderVal = this.minTime;
      this.currentTime = time;
    },
    // 滑块移动时
    changeValue(value) {
      this.sliderVal = value;
      this.currentTime = value;
      // 修改audio的当前播放时间
      this.audioRef.currentTime = value;
    },
    // 处理歌曲基本信息
    reduceMusic(value) {
      let base = null;
      if (value && value.album) {
        base = {
          id: value.id,
          singerName: value.artists,
          songImg: value.album.picUrl,
          songName: `${value.name}${value.alias && value.alias.length ? `（${this.audioId.alias[0]}）` : ''}`
        };
      } else {
        base = {
          id: value.id,
          singerName: value.ar,
          songImg: value.al.picUrl,
          songName: `${value.name}${value.alia && value.alia.length ? `（${this.audioId.alia[0]}）` : ''}`
        };
      }
      this.music = base;
    },
    // 点击上一首、下一首或播放
    playMusic: throttle(function(type) {
      let current =
        this.audioList.findIndex(item => item.id == this.audioId.id);
      if (current === -1) return;
      switch(type) {
        case 'next':
          if (!this.play) {
            this.isPlay = true;
          }
          // 重置播放时长
          this.currentTime = 0;
          
          // 单曲循环
          if (this.playType === 3) {
            this.audioRef.load();
            return;
          }
          
          // 随机播放
          if (this.playType === 4) {
            const anyIndex = randam(0, this.audioList.length - 1);
            this.$store.commit('detail/AUDIOID', this.audioList[anyIndex - 0]);
            this.getMusicUrl();
            return;
          }

          // 当前播放列表最后一首,需重头开始循环
          if (current === this.audioList.length - 1) {
            // 顺序播放
            if (this.playType === 1) {
              this.isPlay = false;
              this.$message.warning('已经是最后一首了');
              return;
            }
            // 说明切换至循环播放
            if (this.playType === 2) {
              const h = this.$createElement;
              this.$message.open({
                icon: h('a-icon', {
                  props: {
                    type: 'coffee'
                  }
                }),
                content: '当前歌曲为播放列表最后一首,即将为你重新播放'
              });
              this.$store.commit('detail/AUDIOID', this.audioList[0]);
            }
          } else {
            this.$store.commit('detail/AUDIOID', this.audioList[current + 1]);
          }
          this.getMusicUrl();
          // 控制歌词loading
          this.$store.commit('main/ISLOAD', true);
          break;
        case 'prev':
          if (!this.play) {
            this.isPlay = true;
          }
          // 重置播放时长
          this.currentTime = 0;

          // 单曲循环
          if (this.playType === 3) {
            this.audioRef.load();
            return;
          }

          // 随机播放
          if (this.playType === 4) {
            const anyIndex = randam(0, this.audioList.length - 1);
            this.$store.commit('detail/AUDIOID', this.audioList[anyIndex - 0]);
            this.getMusicUrl();
            return;
          }

          if (current === 0) {
            this.$store.commit('detail/AUDIOID', this.audioList[this.audioList.length - 1]);
          } else {
            this.$store.commit('detail/AUDIOID', this.audioList[current - 1]);
          }
          this.getMusicUrl();
          // 控制歌词loading
          this.$store.commit('main/ISLOAD', true);
          break;
        default:
          this.isPlay = !this.isPlay;
          
          if (this.duration) {
            this.isPlay ? this.audioRef.play() : this.audioRef.pause();
          } else {
            this.getMusicUrl();
          }
      }
    }, 500),
    // 切换播放模式
    changePlayType: throttle(function() {
      if (this.playType === 4) {
        this.playType = 1;
        return;
      }
      this.playType++;
      let message = '';
      switch(this.playType) {
        case 1:
          message = '已切换至顺序播放';
          break;
        case 2:
          message = '已切换至循环播放';
          break;
        case 3:
          message = '已切换至单曲循环';
          break;
        default:
          message = '已切换至随机播放';
      }
      this.$message.success(message);
    }, 500),

    // 禁音操作
    banNotes(e) {
      e.stopPropagation();
      this.banVolume = !this.banVolume;
      this.audioRef.muted = this.banVolume;
      if (!this.banVolume) {
        this.audioRef.volume = .5;
        this.volume = 50;
        return;
      }
      this.audioRef.volume = 0;
      this.volume = 0;
    },
    // 改变音量大小
    changeVolume(value) {
      this.volume = value;
      // audio中的volume取值只能0-1这个范围
      this.audioRef.volume = value / 100;
      if (!value) {
        this.banVolume = true;
        return;
      }
      this.banVolume = false;
    },
    // 展开侧边展示
    showPlayerList() {
      this.visible = true;
    },
    // 是否显示歌词弹框
    controlModal(show) {
      if (!this.maxTime) {
        this.$message.open({
          icon: this.$createElement('a-icon', {
            props: {
              type: 'smile'
            }
          }),
          content: '点击按钮播放音乐吧！'
        });
        return;
      }
      this.showLyric = show;
    },
    // 跳转到专辑详情,该方法由playInfo组件传递过来
    goAlbum() {
      this.$router.push({
        name: 'albumdetail',
        query: {
          id: this.audioId.al ? this.audioId.al.id : this.audioId.album.id
        }
      });
      this.showLyric = false;
    },
    // 获取播放歌曲
    async getMusicUrl() {
      const res = (await musicUrl(this.audioId.id)).data;
      if (res.code !== 200) return this.$message.error('播放失败');
      if (!res.data[0].url) {
        this.$message.warning('因版权方要求，该资源暂时无法播放，我们正在争取歌曲回归');
        // this.musicUrl = '';
        this.audioRef.src = '';
        this.isPlay = false;
        return;
      }
      // this.musicUrl = res.data[0].url;
      this.audioRef.src = res.data[0].url;
    },
    onClose() {}
  },

  created() {
    // 刷新页面保留上次播放歌曲
    this.$nextTick(() => {
      const song = JSON.parse(localStorage.getItem('currentSong'));
      const list = JSON.parse(localStorage.getItem('recentPlay'));
      // if (song && Object.keys(song).length) {
        
      // 如果是第一次进入,不进行播放
      // this.reduceMusic(song);
      this.$store.commit('main/ISPLAYED', false);
      this.$store.commit('detail/AUDIOID', song);
      this.$store.commit('detail/AUDIOLIST', list);
      // }
    });
  }
}
</script>

<style lang="less" scoped>
.my-audio {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  .player-left {
    width: 25%;
    display: flex;
    align-items: center;
    // justify-content: center;
    img {
      width: 50px;
      height: 50px;
      border-radius: 5px;
      cursor: pointer;
    }
    .player-info {
      width: calc(100% - 60px);
      display: flex;
      margin-left: 10px;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
    }
    .singer-name {
      width: 100%;
    }
    .singer-name>span {
      &::after {
        content: '/';
        display: inline-block;
      }
      &:last-child::after {
        display: none;
      }
    }
  }
  .player-center {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 50%;
    .player-bar {
      width: 300px;
      // margin: 0 auto;
      display: flex;
      justify-content: space-around;
      // align-items: center;
      // margin-top: 6px;
      button {
        background: unset;
        border: none;
        cursor: pointer;
        i {
          font-size: 18px;
          &:hover {
            color: #ec4141;
          }
        }
      }
      .iconfont:hover {
        color: #ec4141;
      }
      .disabled-color {
        color: #9b9b9b;
        cursor: default;
      }
    }
    // .player-progress {
    //   display: flex;
    //   align-items: center;
    //   /deep/.ant-slider {
    //     width: 400px;
    //     // height: 3px !important;
    //     margin: 0 10px;
    //   }
    // }
  }
  .player-right {
    width: 30%;
    display: flex;
    justify-content: flex-end;
    button {
      position: relative;
      background: unset;
      border: none;
      cursor: pointer;
      margin-right: 30px;
      &:last-child {
        margin-right: 0;
      }
      i {
        font-size: 24px;
      }
      .hover-modal {
        position: absolute;
        top: -115px;
        left: -50%;
        width: 45px;
        background: rgb(255, 255, 255);
        // height: 300px;
        box-shadow: rgb(136 136 136) 0px 2px 10px;
        border-radius: 5px;
        z-index: 1000;
        &::after {
          content: '';
          /* display: block; */
          position: absolute;
          /* margin-left: 10px; */
          width: 0;
          height: 0;
          left: 50%;
          transform: translateX(-50%);
          bottom: -10px;
          border-width: 6px;
          border-style: solid;
          /* box-shadow: #888888 0px 2px 10px; */
          /* border-radius: 3px; */
          border-color: #fff transparent transparent transparent;
        }
      }
    }
  }
  // div {
  //   &:last-child {
  //     display: contents;
  //   }
  // }
  // 抽屉内样式
  .list-header {
    display: flex !important;
    justify-content: space-around;
    align-items: center;
    .total-song {
      color: #cfcfcf;
    }
  }
}
</style>
<style lang="less" scoped>
.my-audio {
  /deep/.ant-drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: none;
    padding: 24px 10px !important;
  }
  /deep/.ant-drawer-body {
    height: calc(100vh - 80px);
    overflow-y: auto;
    padding: 10px !important;
  }
  /deep/.ant-table {
    margin-top: 30px;
    border-top: 1px solid #e6e6e6;
  }
  /deep/.ant-table-placeholder {
    padding: 50px 0;
    border-top: none;
  }
  /deep/.ant-table-tbody > tr > td {
    border-bottom: none;
  }
}
</style>